/*
 * @Description: 
 * @version: 
 * @Author: 171
 * @Date: 2022-09-07 19:39:34
 * @LastEditors: 171
 * @LastEditTime: 2022-09-22 18:30:12
 */
import express, {
  Router,
  Request,
  Response,
} from "express";
import qs from "qs";
import connection  from "../db"; // 获取连接实例
import MYCRYPTO from "../encrypt/aes";

const articleRouter: Router = express.Router(); // 声明一个路由，获取自定义api

articleRouter.get("/", (req: Request, res: Response) => { // 用于获取用户的所有文章
  
  const { id, page, number }: any = qs.parse(req.query.reqData as string);

  const sql = `select * from article where userId = '${id}' order by id desc limit ${(page - 1) * number},${number};`;

  connection.query(sql, (err: any, result: any) => {
    if (err) {
      const errorRes = qs.stringify({ message: "error", error: err, code: 1 });
      res.send(errorRes);
    } 
    else { 
      result.forEach((item: any) => {
        item.title = MYCRYPTO.decrypt(item.title);
        item.description = MYCRYPTO.decrypt(item.description);
        item.content = MYCRYPTO.decrypt(item.content);
      });
      const dataRes = qs.stringify({ message: 'ok', data: result, code: 0 });
      res.send(dataRes);
    }
  })
});


articleRouter.post("/", (req: Request, res: Response) => { // 用于添加用户文章

  const { userId, title, content, publishTime, description } = qs.parse(req.body.reqData as string);
  
  const sql = `insert into article (userId, title, description, content, publishTime) values ('${userId}', '${MYCRYPTO.encrypt(title)}', '${MYCRYPTO.encrypt(description)}', '${MYCRYPTO.encrypt(content)}', '${publishTime}')`;
  
  connection.query(sql, (err: any, result: any) => {
    if (err) {
      const errorRes = qs.stringify({ message: "error", error: err, code: 1 });
      res.send(errorRes);
    } 
    else { 
      const dataRes = qs.stringify({ message: 'ok', code: 0 });
      res.send(dataRes);
    }
  })
});

export default articleRouter;